package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.base.BaseResult;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.model.Event;
import com.cardbaobao.cardbabyclient.model.RealName;
import com.cardbaobao.cardbabyclient.model.UserInfo;
import com.cardbaobao.cardbabyclient.model.result.HasBindCardResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.LoansUtils;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/4 15:27.
 */

public class BankCardVerifyActivity extends BaseActivity {
    public static final String CARD_NAME_S = "cardName";
    public static final String CARD_ID_S = "cardId";

    public static final String PAGE_FROM_I = "activity_type";//需要绑储蓄卡的页面

    public static final int ACTIVITY_QUICK_DEBIT = 1;//快捷收款页面添加储蓄卡
    public static final int ACTIVITY_QR_CODE_DEBIT = 2;//二维码收款页面添加储蓄卡
    public static final int ACTIVITY_CARD_MANAGE_ADD = 3;//银行卡管理添加储蓄卡
    public static final int ACTIVITY_CARD_MANAGE_REPLACE = 4;//银行卡管理更换储蓄卡
    public static final int ACTIVITY_REPAYMENT = 5;//信用卡还款页面添加银行卡

    private static final int COUNT_DOWN_TOTAL = 60;//倒计时60s
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.tv_bank_card_type)
    TextView tvBankCardType;
    @BindView(R.id.et_phone_number)
    EditText etPhoneNumber;
    @BindView(R.id.et_verify_code)
    EditText etVerifyCode;
    @BindView(R.id.bt_send_verify_code)
    Button btSendVerifyCode;
    @BindView(R.id.bt_next_step)
    Button btNextStep;

    private String cardTypeId;
    private String name;
    private String idCardNo;
    private String cardNumber;

    private String phoneNumber;
    private String verifyCode;

    private int countDownTime;
    Handler handler;

    int pageFrom;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bank_card_verify;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ImmersionBar.with(this).keyboardEnable(true).init();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        handler = new Handler();
        Intent intent = getIntent();

        mCurrentPageId = "app_bank_verification";

        name = intent.getStringExtra(IdentifyVerifyActivity.NAME_S);
        idCardNo = intent.getStringExtra(IdentifyVerifyActivity.ID_CARD_NO_S);
        cardNumber = intent.getStringExtra(IdentifyVerifyActivity.CARD_NUMBER_S);
        cardTypeId = intent.getStringExtra(CARD_ID_S);

        String cardName = intent.getStringExtra(CARD_NAME_S);
        tvBankCardType.setText(cardName + " 储蓄卡");

        pageFrom = intent.getIntExtra(PAGE_FROM_I, 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName("添加储蓄卡-银行认证");
    }

    //检查手机号码
    private boolean checkPhone() {
        boolean result = true;
        String phoneNumber = etPhoneNumber.getText().toString().trim();
        if (!RegularUtil.isPhoneNumber(phoneNumber)) {
            result = false;
            ToastUtil.showToast("手机号码格式不正确，请重新填写");
        }
        return result;
    }

    //开始倒计时
    private void startCountDown() {
        countDownTime = COUNT_DOWN_TOTAL;
        handler.postDelayed(runnable, Constant.ONE_SECOND);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (countDownTime > 0) {
                countDownTime--;
                btSendVerifyCode.setText(countDownTime + "s后重发");
                handler.postDelayed(this, Constant.ONE_SECOND);
            } else {
                btSendVerifyCode.setText("发送验证码");
                btSendVerifyCode.setEnabled(true);
            }
        }
    };

    private boolean checkVerifyCode() {
        String verifyCode = etVerifyCode.getText().toString().trim();
        if (verifyCode.length() == 0) {
            ToastUtil.showToast("请填写验证码");
            return false;
        }
        if (!verifyCode.equals(this.verifyCode)) {
            ToastUtil.showToast("验证码错误");
            return false;
        }
        return true;
    }

    @OnTextChanged({R.id.et_phone_number})
    public void afterPhoneTextChange(Editable s) {
        if (s.toString().trim().length() == 11) {
            if (etVerifyCode.getText().toString().trim().length() > 0) {
                btNextStep.setEnabled(true);
            }
        } else {
            btNextStep.setEnabled(false);
        }
    }

    @OnTextChanged({R.id.et_verify_code})
    public void afterVerifyCodeTextChange(Editable s) {
        if (s.toString().trim().length() > 0 && etPhoneNumber.getText().toString().trim().length() == 11) {
            btNextStep.setEnabled(true);
        } else {
            btNextStep.setEnabled(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    private void sendVerifyCode(String phoneNumber) {
        showProgressDialog(false);
        this.phoneNumber = phoneNumber;
        this.verifyCode = String.valueOf(LoansUtils.getMsgCode());
        Api.sendSms(phoneNumber, Constant.VERIFY_CODE_TYPE, verifyCode, Constant.GDX030104).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        handlerSmsFailure();
                        ToastUtil.showToast("获取验证码失败，请稍后重试");
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        JSONObject json = JSON.parseObject(s);
                        if (1 == json.getIntValue("status")) {
                            //发送验证码成功
                            startCountDown();
                        } else {
                            ToastUtil.showToast(json.getString("result"));
                            handlerSmsFailure();
                        }
                    }
                });
    }

    private void handlerSmsFailure() {
        verifyCode = null;
        btSendVerifyCode.setEnabled(true);
    }

    //绑卡
    private void bindCard() {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        params.put("member_id", String.valueOf(mApplication.getUser().getID()));
        params.put("card_type_id", cardTypeId);
        params.put("id_number", idCardNo);
        params.put("account_name", name);
        params.put("card_number", cardNumber);
        params.put("account_mobile", phoneNumber);
        Api.bindDebitCard(params).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                BaseResult result = JsonUtil.json2Object(s, BaseResult.class);
                if (result.getCode() == Constant.SUC_CODE) {
                    //绑卡成功
                    //将实名认证信息写到本地
                    UserInfo userInfo=mApplication.getUser();
                    userInfo.setTrueName(name);
                    userInfo.setIDCardNo(idCardNo);
                    if (pageFrom == ACTIVITY_QUICK_DEBIT) {
                        //快捷收款添加储蓄卡
                        queryBindCreditCard();
                    } else if (pageFrom == ACTIVITY_QR_CODE_DEBIT) {
                        //二维码收款页面添加储蓄卡
                        dismissProgressDialog();
                        Intent intent = new Intent(mContext, BindCardSuccessActivity.class);
                        intent.putExtra(DebitIntroActivity.DEBIT_TYPE_I,
                                DebitIntroActivity.QR_CODE_DEBIT);
                        intent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                        startActivity(intent);
                        finish();
                    } else if (pageFrom == ACTIVITY_CARD_MANAGE_ADD) {
                        //银行卡管理页面添加储蓄卡
                        dismissProgressDialog();
                        ToastUtil.showToast("储蓄卡绑定成功");
                        EventBus.getDefault().post(new Event.BindDebitCardSuccess());
                        finish();
                    } else if (pageFrom == ACTIVITY_CARD_MANAGE_REPLACE) {
                        //银行卡管理页面更换储蓄卡
                        dismissProgressDialog();
                        Intent intent = new Intent(mContext,
                                ReplaceCardSuccessActivity.class);
                        startActivity(intent);
                        finish();
                    } else if (pageFrom == ACTIVITY_REPAYMENT) {
                        //信用卡还款页面添加储蓄卡
                        dismissProgressDialog();
                        Intent intent = new Intent(mContext, AddDepositCardResultActivity.class);
                        intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(intent);
                        finish();
                        EventBus.getDefault().post(new Event.BindCardRepaySuc());
                    }
                } else {
                    dismissProgressDialog();
                    ToastUtil.showToast(result.getMsg());
                }
            }
        });
    }

    private void queryBindCreditCard() {
        Api.checkBindCard(String.valueOf(mApplication.getUser().getID())).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast("储蓄卡绑定成功");
                        finish();
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        HasBindCardResult result = JsonUtil.json2Object(s, HasBindCardResult.class);
                        if (result.getCode() == 1) {
                            //已实名，已绑定储蓄卡，信用卡
                            Intent intent = new Intent(mContext, BindCardSuccessActivity.class);
                            intent.putExtra(DebitIntroActivity.DEBIT_TYPE_I,
                                    DebitIntroActivity.QUICK_DEBIT);
                            intent.putExtra(BindCardSuccessActivity.NEED_BIND_CREDIT_CARD_B,
                                    false);
                            intent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                            startActivity(intent);
                        } else if (result.getCode() == 3) {
                            //已实名，未绑定信用卡
                            Intent intent = new Intent(mContext, BindCardSuccessActivity.class);
                            intent.putExtra(DebitIntroActivity.DEBIT_TYPE_I,
                                    DebitIntroActivity.QUICK_DEBIT);
                            intent.putExtra(BindCardSuccessActivity.NEED_BIND_CREDIT_CARD_B,
                                    true);
                            RealName realName = result.getData();
                            intent.putExtra(AddCreditCardActivity.NAME_S,
                                    realName.getTrue_name());
                            intent.putExtra(AddCreditCardActivity.ID_CARD_NO_S,
                                    realName.getId_card_no());
                            intent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                            startActivity(intent);
                        }
                        finish();
                    }
                });
    }

    @OnClick({R.id.bt_send_verify_code, R.id.bt_next_step})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_send_verify_code:
                //发送验证码
                if (checkPhone()) {
                    String inputPhoneNumber = etPhoneNumber.getText().toString().trim();
                    btSendVerifyCode.setEnabled(false);
                    sendVerifyCode(inputPhoneNumber);
                }
                break;
            case R.id.bt_next_step:
                //埋点
                SelfUtils.buriedClickData(Self.Action.app_click_bank_verification_nextstep,
                        Self.Action.app_click_bank_verification_nextstep_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                if (checkPhone() && checkVerifyCode()) {
                    if (etPhoneNumber.getText().toString().trim().equals(phoneNumber)) {
                        if (TextUtils.isEmpty(cardTypeId)) {
                            ToastUtil.showToast("请选择卡片类型");
                        } else {
                            bindCard();//开始绑卡
                        }
                    } else {
                        ToastUtil.showToast("非法操作");
                    }
                }
                break;
        }
    }
}
